package com.mdc.mansion.common.util;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;

/**
 * 设置序列化为json时，自定义的转换
 * 
 * @author: chenggui.huang
 * @date: 2014-02-18 14:38
 */
public class JSONUtil extends ObjectMapper {
	private static ObjectMapper objectMapper = new JSONUtil();
	private static final String LONG_DATE_FORMAT_STR = "yyyy-MM-dd HH:mm:ss";
	public JSONUtil() {
		super();
		SimpleModule simpleModule = new SimpleModule("simpleModule", Version.unknownVersion());
		simpleModule.addSerializer(Date.class, new JsonSerializer<Date>() {
			@Override
			public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
				SimpleDateFormat formatter = new SimpleDateFormat(LONG_DATE_FORMAT_STR);
				String formattedDate = formatter.format(value);
				jgen.writeString(formattedDate);
			}
		});
		simpleModule.addSerializer(Timestamp.class, new JsonSerializer<Timestamp>() {
			@Override
			public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
				SimpleDateFormat formatter = new SimpleDateFormat(LONG_DATE_FORMAT_STR);
				String formattedDate = formatter.format(value);
				jgen.writeString(formattedDate);
			}
		});
		simpleModule.addSerializer(BigDecimal.class, new JsonSerializer<BigDecimal>() {
			@Override
			public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
				DecimalFormat df = new DecimalFormat("###########0.####");
				jgen.writeString(df.format(value));
			}
		});
		simpleModule.addSerializer(Double.class, new JsonSerializer<Double>() {
			@Override
			public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
				DecimalFormat df = new DecimalFormat("###########0.####");
				jgen.writeString(df.format(value));
			}
		});
		getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
				jg.writeString("");
			}
		});
		registerModule(simpleModule);
	}

	public static ObjectMapper getInstance() {
		return objectMapper;
	}
}
